package com.tosit.driverschool.controller;

import com.tosit.driverschool.common.entity.Subject;
import com.tosit.driverschool.service.SubjectService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import java.util.Arrays;
import java.util.List;

@Controller
@RequestMapping("/subject")
public class    SubjectController {

    @Autowired
    SubjectService subjectService;

    @GetMapping("/list")
    public String list(ModelMap modelMap){
        List<Subject> all = subjectService.findAll();

        modelMap.put("subjects", all);
        modelMap.put("content", "subject-list");
        System.out.println("_______________________________");

        return "index";
    }

    @GetMapping("/deleteById")
    public String deleteById(Integer id){
        subjectService.deleteById(id);
        return "redirect:/subject/list";
    }

    @GetMapping("/deleteByIds")
    @ResponseBody
    public String deleteByIds(String ids){
        String[] idList = ids.split(",");
        List<String> list = Arrays.asList(idList);
        subjectService.deleteByIds(list);

        return "SUCCESS";
    }

    //跳转到填写题目的表单
    @GetMapping("/addSubject")
    public String addSubject(ModelMap modelmap){
        modelmap.put("content", "new-subject");

        return "index";
    }

    //处理填写好的题目表单
    @PostMapping("/saveSubject")
    public String saveSubject(HttpServletRequest req){
        subjectService.saveSubject(req);

        return "redirect:/subject/list";
    }
}
